import { ref, onMounted, onBeforeUnmount, onUnmounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { routes as moduleArr } from '@/router/index'
import { apiConfigurable } from '@/request/api/api'
export const useSms = () => {
    let sms = ref("");
    let smsText = ref("发送验证码");
    let smsNum = ref(60);
    let smsTimer = null;
    let isSended = ref(false)


    function smsCounter() {
        isSended.value = true

        smsTimer = setInterval(() => {
            if (smsNum.value > 0) {
                smsNum.value--;
                smsText.value = smsNum.value + "秒后重发";
            } else {
                smsNum.value = 60;
                smsText.value = "重新发送";
                clearInterval(smsTimer);
            }
        }, 1000);

    }

    // onMounted(() => {
    //     console.log("hooks---onMounted");
    // });
    // onBeforeUnmount(() => {
    //     console.log("hooks---onMounted");
    // });
    // onUnmounted(() => {
    //     console.log("hooks---onUnmounted");
    // });

    return {
        sms, smsText, smsNum, smsTimer, smsCounter, isSended
    };
};

export const useCheck = () => {
    function checkCustomized(path) {
        return moduleArr.some(item => item.path === path)
    }
    return {
        checkCustomized
    }
}

//字段联动
export const useFieldLinkage = () => {
    const controlLinkArr = ref([]);
    let orginData = reactive({})


    function getFieldLink(orgData) {
        let masterControlFiles = []
        let allFields = []
        let controlLinkArr = []

        for (let i = 0; i < orgData.head.length; i++) {
            allFields = [...allFields, ...orgData.head[i].groupvalue]
        }

        masterControlFiles = allFields.filter(item => {
            return item.sFormat.indexOf('fs_field') !== -1
        })

        const fsMasterArr = []
        // console.log("masterControlFiles", masterControlFiles)

        masterControlFiles = masterControlFiles.map(item => {
            fsMasterArr.push(item.sField)
            const fsArr = item.sFormat.split(';').filter(item => {
                return item.indexOf('fs_') !== -1
            }).map(item => item.split(':')).map(item => {
                if (item[1]) {
                    item[1] = item[1].split(',')
                }
                return item
            })
            return Object.fromEntries(fsArr)
        }).map((item, index) => {
            item.fs_master = new Array(item.fs_field?.length)
            item.fs_master.fill(fsMasterArr[index])
            return item
        })
        console.log("masterControlFiles", masterControlFiles)

        for (let i = 0; i < masterControlFiles.length; i++) {
            if (Array.isArray(masterControlFiles[i].fs_field)) {
                for (let j = 0; j < masterControlFiles[i].fs_field.length; j++) {
                    const obj = {}
                    for (let key in masterControlFiles[i]) {
                        obj[key] = masterControlFiles[i][key][j]
                    }
                    controlLinkArr.push(obj)
                }
            } else {
                controlLinkArr.push(masterControlFiles[i])
            }
        }


        return controlLinkArr
    }



    function handleFiledLink(masterObj, jsondata, orginData) {
        const filedLinkRule = controlLinkArr.value.filter(item => {
            return item.fs_master == masterObj.sField
        })



        if (filedLinkRule.length > 0) {
            // console.log("filedLinkRule", filedLinkRule)
            for (let i = 0; i < jsondata.head.length; i++) {
                for (let j = 0; j < jsondata.head[i].groupvalue.length; j++) {
                    const currentItem = jsondata.head[i].groupvalue[j]
                    const orginDataItem = orginData.head[i].groupvalue[j]
                    let count = 0


                    filedLinkRule.forEach(fitem => {
                        if (jsondata.head[i].groupvalue[j].sField === fitem.fs_field) {
                            if (flLogicalJudgment(masterObj.value, fitem)) {
                                currentItem.lCanInput = fitem.fs_disabled == '1' ? '0' : '1'
                                currentItem.lCanOutput = fitem.fs_show == '1' ? '0' : '1'
                                currentItem.lMustInput = fitem.fs_must
                                count++
                            }
                        }
                    })
                    if (count === 0) {
                        currentItem.lCanInput = orginDataItem.lCanInput
                        currentItem.lCanOutput = orginDataItem.lCanOutput
                        currentItem.lMustInput = orginDataItem.lMustInput
                    }


                }
            }



            if (jsondata.bodydata) {
                for (let bodydatakey in jsondata.bodydata) {
                    let body = jsondata.body[bodydatakey]
                    let bodydata = jsondata.bodydata[bodydatakey]
                    let orginbodydata = orginData.body[bodydatakey]
                    for (let i = 0; i < bodydata.length; i++) {
                        for (let j = 0; j < bodydata[i].length; j++) {
                            let count = 0 //联动计数器
                            filedLinkRule.forEach(fitem => {
                                if (bodydata[i][j].sField + '_b' === fitem.fs_field) {
                                    if (flLogicalJudgment(masterObj.value, fitem)) {
                                        body[j].lCanInput = fitem.fs_disabled == '1' ? '0' : '1'
                                        body[j].lCanOutput = fitem.fs_show == '1' ? '0' : '1'
                                        body[j].lMustInput = fitem.fs_must
                                        bodydata[i][j].lCanInput = fitem.fs_disabled == '1' ? '0' : '1'
                                        bodydata[i][j].lCanOutput = fitem.fs_show == '1' ? '0' : '1'
                                        bodydata[i][j].lMustInput = fitem.fs_must
                                        count++
                                    }
                                }
                            })
                            if (count === 0) {
                                body[j].lCanInput = orginbodydata[j].lCanInput
                                body[j].lCanOutput = orginbodydata[j].lCanOutput
                                body[j].lMustInput = orginbodydata[j].lMustInput
                                bodydata[i][j].lCanInput = orginbodydata[j].lCanInput
                                bodydata[i][j].lCanOutput = orginbodydata[j].lCanOutput
                                bodydata[i][j].lMustInput = orginbodydata[j].lMustInput
                            }
                        }
                    }
                }
            }
        }


    }

    function flLogicalJudgment(masterValue, ruleObj) {
        let res = false
        // 等于
        if (ruleObj.fs_type === 'eq' && masterValue === ruleObj.fs_value) {
            res = true
        }
        // 包含判断
        if (ruleObj.fs_type === 'contain' && masterValue.indexOf(ruleObj.fs_value) !== -1) {
            res = true
        }

        // 长度大于
        if (ruleObj.fs_type === 'big' && masterValue.length > ruleObj.fs_value) {
            res = true
        }

        // 长度大于等于
        if (ruleObj.fs_type === 'bigeq' && masterValue.length >= ruleObj.fs_value) {
            res = true
        }

        // 长度等于
        if (ruleObj.fs_type === 'leneq' && masterValue.length == ruleObj.fs_value) {
            res = true
        }

        // 长度小于等于
        if (ruleObj.fs_type === 'smalleq' && masterValue.length <= ruleObj.fs_value) {
            res = true
        }

        // 长度小于
        if (ruleObj.fs_type === 'small' && masterValue.length < ruleObj.fs_value) {
            res = true
        }

        return res
    }

    return {
        controlLinkArr,
        orginData,
        getFieldLink,
        handleFiledLink,
        flLogicalJudgment
    }
}

//字段映射
export const useFieldMap = () => {

    //映射处理
    function handleFiledMap(jsondata, refmap, mapObject, tableType, bodyDataName = "", bodyDataIndex = "") {
        // jsondata:数据源 refmap:映射关系 mapObject:映射对象 tableType:表类型(表头or标题) bodyDataName:表体名 bodyDataIndex:表体名索引
        const data = tableType === 'head' ? jsondata.value.head : jsondata.value.bodydata[bodyDataName][bodyDataIndex]
        const mapField = []
        for (let key in refmap) {
            if (key.indexOf(`${mapObject}_`) !== -1) {
                const fieldArr = key.split(/_(.*)$/, 2);
                mapField.push(fieldArr[1])
            }
        }

        if (tableType === 'head') {
            for (let i = 0; i < data.length; i++) {
                for (let j = 0; j < data[i].groupvalue.length; j++) {


                    if (mapField.indexOf(data[i].groupvalue[j].sField) !== -1) {
                        // console.log(data[i].groupvalue[j].sField)

                        switch (data[i].groupvalue[j].sUIType) {
                            case 'ref':
                                data[i].groupvalue[j].value = refmap[`${mapObject}_${data[i].groupvalue[j].sField}_ref`]
                                data[i].groupvalue[j].valuehidden = refmap[`${mapObject}_${data[i].groupvalue[j].sField}`]
                                break
                            case 'enum':
                                data[i].groupvalue[j].value = refmap[`${mapObject}_${data[i].groupvalue[j].sField}_enum`]
                                data[i].groupvalue[j].valuehidden = refmap[`${mapObject}_${data[i].groupvalue[j].sField}`]
                                break
                            case 'bool':
                                data[i].groupvalue[j].value = refmap[`${mapObject}_${data[i].groupvalue[j].sField}`] == '1' ? '是' : '否'
                                break
                            default:
                                data[i].groupvalue[j].value = refmap[`${mapObject}_${data[i].groupvalue[j].sField}`]
                                break
                        }
                    }
                }
            }
        }

        if (tableType === 'body') {
            for (let i = 0; i < data.length; i++) {
                if (mapField.indexOf(data[i].sField) !== -1) {
                    switch (data[i].sUIType) {
                        case 'ref':
                            data[i].value = refmap[`${mapObject}_${data[i].sField}_ref`]
                            data[i].valuehidden = refmap[`${mapObject}_${data[i].sField}`]
                            break
                        case 'enum':
                            data[i].value = refmap[`${mapObject}_${data[i].sField}_enum`]
                            data[i].valuehidden = refmap[`${mapObject}_${data[i].sField}`]
                            break
                        case 'bool':
                            data[i].value = refmap[`${mapObject}_${data[i].sField}`] === '1' ? '是' : '否'
                            break
                        default:
                            data[i].value = refmap[`${mapObject}_${data[i].sField}`]
                            break
                    }
                }
            }
        }
    }


    //获取映射关系
    function getMapInfo(data) {
        return apiConfigurable('ref.select.do', data)
    }

    return {
        handleFiledMap,
        getMapInfo
    }

}






